package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.PhoneUserEntivity;
import com.sam.im.heiqun.entities.PhoneUserSQLEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.activities.phonecontact.*;
import com.sam.im.heiqun.uis.beans.ContactBean;
import com.sam.im.heiqun.uis.beans.ContactImportEntity;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.RefreshAndLoad.PullToRefreshLayout;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 手机联系人
 */
public class ContactActivity extends BaseSwipeBackActivity    {

    private static final String TAG = ContactActivity.class.getSimpleName();
//
    private List<PhoneUserSQLEntivity> mPhoneSQLUsers = new ArrayList<>();
    PhoneUserSQLEntivity mPhoneUserSQLEntivity;

    private List<ContactBean> data = new ArrayList<>();
    private PhoneLinkAdapter adapter;

    @BindView(R.id.list_phone_user)
    RecyclerView list_friend;
    @BindView(R.id.pre_v_back)
    ImageView pre_v_back;
    @BindView(R.id.phone_constant_refresh)
    PullToRefreshLayout plContent;

    private PGService mPGservice;
    private int showCount = 20;
    private int nowCount = 0;

    @Override
    public int getContentViewId() {
        return R.layout.activity_phone_users_list;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.add_mobile_linkman);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        mPGservice = PGService.getInstance();

        list_friend.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        adapter = new PhoneLinkAdapter(this, data);
        list_friend.setAdapter(adapter);
        adapter.setOnClickListener(new PhoneLinkAdapter.OnClickListener() {
            @Override
            public void OnClick(ContactBean noticeBean, int type) {
                switch (type){
                    case 0 :
                        String name = noticeBean.getNickName();
                        if (null==name || "".equals(name)){
                            name = noticeBean.getMarkName();
                        }
                        PhoneUserDetailsActivity.startActivity(ContactActivity.this,name,noticeBean.getPhone(),noticeBean.getIsExists(),noticeBean.getHeader());

                        break;
                    case 1 :
                        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + noticeBean.getPhone()));
                        intent.putExtra("sms_body", getResources().getString(R.string.yaoqing_send_message));
                        startActivity(intent);
                        doBind(noticeBean.getPhone());
                        break;
                }

            }
        });

        plContent.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onPullDownToRefresh() {
                nowCount = 0 ;
                getLinkMenThread(ContactActivity.this,showCount,nowCount);
            }
            @Override
            public void onPullUpToRefresh() {
                getLinkMenThread(ContactActivity.this,showCount,nowCount);
            }
        });
        plContent.autoRefresh();
    }

    /**
     * 用户与被推荐人的绑定
     */
    private void doBind(String phone) {
        String userId = ToolsUtils.getPhpUid();
        mPGservice.setrefer(userId, phone).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.e(TAG, "onResultError:  绑定推荐人失败");
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                showToast(getResources().getString(R.string.bang_tuijian_success));
            }
        });
    }

    private void getLinkMenThread(Context context, int showCount, int nowCount) {
        showProgress(getResources().getString(R.string.now_down));
        final List<PhoneUserEntivity> models = ToolsUtils.getContactsByPage(getContentResolver(), context, showCount, nowCount);
        if (models.size() <= 0) {//已经是最后了，不能再加载了
            Log.i(TAG, "getLinkMenThread: ---------------0001--------");
            hideProgress();
            plContent.stopLoading();
        }else {
            Log.i(TAG, "getLinkMenThread: ---------------0002--------");
            mPhoneSQLUsers.clear();
            for (int i = 0; i < models.size(); i++) {
                PhoneUserEntivity phoneUserEntivity = models.get(i);
                mPhoneUserSQLEntivity = new PhoneUserSQLEntivity(phoneUserEntivity.getName(),phoneUserEntivity.getNumber());
                mPhoneSQLUsers.add(mPhoneUserSQLEntivity);
            }
        }
        Log.i(TAG, "getLinkMenThread: ---------------0003--------");
        if (null!=mPhoneSQLUsers && mPhoneSQLUsers.size() > 0){
            Log.i(TAG, "getLinkMenThread: ---------------0004--------");
            importPhone(new Gson().toJson(mPhoneSQLUsers));
        }
    }

    @OnClick({R.id.pre_v_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
        }
    }

//    /**
//     * 检测手机联系人是否已经注册过了
//     */
//    private void myContact(String phones) {
//        Log.i(TAG, "getLinkMenThread: ---------------0005--------phones="+phones);
//        mPGservice.myContact(phones, ToolsUtils.getPhpUid(),"1").subscribe(new AbsAPICallback<String>() {
//            @Override
//            protected void onResultError(ApiException ex) {
//                handler.sendEmptyMessage(HIDEPROGRESS);
//                Log.i(TAG, "onNext: -----0006---1--="+ex.getCode());
//                Log.i(TAG, "onNext: -----0006---2--="+ex.getDisplayMessage());
//                Log.i(TAG, "onNext: -----0006---3--="+ex.getMessage());
////                runOnUiThread(new Runnable() {
////                    @Override
////                    public void run() {
////                        showToast("验证提交失败!");
////                    }
////                });
//                handler.sendEmptyMessage(REFRESH);
//
//                handler.sendEmptyMessage(HIDEPROGRESS);
//            }
//
//            @Override
//            public void onNext(String string) {
//                handler.sendEmptyMessage(HIDEPROGRESS);
//                Log.i(TAG, "onNext: ----0007------string="+string);
////                mAdapter.notifyDataSetChanged();
////
////                handler.sendEmptyMessage(REFRESH);
////
////                handler.sendEmptyMessage(HIDEPROGRESS);
//
//            }
//        });
//    }
    /**
     * 检测手机联系人是否已经注册过了
     */
    private void importPhone(String phones) {
        Log.i(TAG, "getLinkMenThread: ---------------0005--------phones="+phones);
        mPGservice.importPhone(phones, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ContactImportEntity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                plContent.stopLoading();
            }

            @Override
            public void onNext(ContactImportEntity string) {
                Log.i(TAG, "onNext: ----0007------string="+string);
                if (0==nowCount){
                    data.clear();
                }
                int start = data.size();
                if (null==string || null==string.getInfo() || string.getInfo().size()<=0){
                    for (int i = 0; i < mPhoneSQLUsers.size(); i++) {
                        ContactBean contact = new ContactBean();
                        contact.setIsExists("0");
                        contact.setMarkName(mPhoneSQLUsers.get(i).getMarkName());
                        contact.setPhone(mPhoneSQLUsers.get(i).getPhone());
                        data.add(contact);
                        nowCount = nowCount + mPhoneSQLUsers.size();
                    }
                }else {
                    data.addAll(string.getInfo());
                    nowCount = nowCount + string.getInfo().size();
                }
                int end = data.size() -1 ;
//                adapter.notifyItemRangeInserted(start, end);
                adapter.notifyDataSetChanged();
                hideProgress();

                plContent.stopLoading();
            }
        });
    }
}
